package com.crm.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.crm.dao.MenuDAO;
import com.crm.po.Menu;
import com.crm.util.RequestEx;

public class MenuService {

	private static Logger logger = Logger.getLogger(MenuService.class);
	
	public List<Menu> getTreeByType(String treeType){
		String Hql = "from Menu t where 1=1 and t.menutype = '" + treeType + "' order by t.sort ";
		MenuDAO dao = new MenuDAO();
	    List<Menu> list = dao.menuList(Hql);
	    return list;
	}
	
	public List<Menu> getMenuList(String treeType){
		String Hql = "from Menu t where 1=1 and t.menutype = '" + treeType + "' order by t.sort ";
		MenuDAO dao = new MenuDAO();
	    List<Menu> list = dao.menuList(Hql);
	    return list;
	}
	
	public boolean saveOrUpdateMenu(HttpServletRequest request){
		try{
			String id = RequestEx.getStringTrim(request.getParameter("id"));
			String text = RequestEx.getStringTrim(request.getParameter("text"));
			Integer sort = RequestEx.getInteger(request.getParameter("sort"));
			String menutype = RequestEx.getStringTrim(request.getParameter("menutype"));
			
			MenuDAO dao = new MenuDAO();
			Menu menu = null;
			if(id != null && id.trim().length() > 0){
				menu = dao.findById(id);
			}else{				
				menu = new Menu();
			}
			
			menu.setText(text);
			menu.setSort(sort);
			menu.setMenutype(menutype);
						
			dao.saveOrUpdate(menu);
		}catch(Exception e){
			logger.error("save or update menu fail:", e);
			return false;
		}
	    return true;
	}
	
	public int deleteMenu(HttpServletRequest request){
		int result = 0;
		String ids = RequestEx.getStringTrim(request.getParameter("ids"));		
		try{
			if(ids.length() > 0){
				MenuDAO dao = new MenuDAO();
				
				String hql1 = "select count(*) from Customer T WHERE T.cGroup IN (" + ids + ")";
				String hql2 = "select count(*) from Inventory T WHERE T.cGroup IN (" + ids + ")";
				
				int cusCount = dao.getCount(hql1);
				int invCount = dao.getCount(hql2);
				
				if((cusCount + invCount) > 0){
					return -1;
				}	
				
				String hql3 = "DELETE FROM Menu T WHERE T.id IN (" + ids + ")";
				
				result = dao.executeHql(hql3);
			}			
		}catch(Exception e){
			logger.error("delete menu fail:", e);
			return -2;
		}
	    return result;
	}
	
}
